package lock

import (
	"context"
	"time"

	"catering_sys_api/core/db"

	"github.com/bsm/redislock"
)

type Lock struct {
	key     string
	timeout int //毫秒

	ctx  context.Context
	lock *redislock.Lock
}

func NewLock(key string, timeout int, ctx context.Context) *Lock {
	return &Lock{
		key:     key,
		timeout: timeout,
		ctx:     ctx,
	}
}

func (t *Lock) Lock() bool {
	var (
		err    error
		locker *redislock.Client
	)

	locker = redislock.New(db.Reids)
	t.ctx = context.Background()
	t.key = "lock:" + t.key

	if t.timeout == 0 {
		t.timeout = 3000 //默认3s
	}
	t.lock, err = locker.Obtain(t.ctx, t.key, time.Duration(t.timeout)*time.Millisecond, nil)

	if err == redislock.ErrNotObtained {
		return false
	} else if err != nil {
		return false
	}
	return true
}

func (t *Lock) UnLock() bool {

	err := t.lock.Release(t.ctx)
	if err != nil {
		return false
	}
	return true
}

func (t *Lock) Refresh() bool {
	err := t.lock.Refresh(t.ctx, time.Duration(t.timeout)*time.Millisecond, &redislock.Options{
		RetryStrategy: redislock.NoRetry(),
	})

	if err != nil {
		return false
	}

	return true
}
